package com.example.homemodule.adapter;

import static com.yilijk.base.utils.ThreadUtils.runOnUiThread;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.examination.mlib.view.autoscrollviewpager.AutoScrollViewPager;
import com.examination.mlib.view.autoscrollviewpager.RecyclingPagerAdapter;
import com.example.homemodule.R;
import com.example.homemodule.model.bean.HomepageEntity;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.UIUtils;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class DoctorHealthAdapter extends RecyclingPagerAdapter implements ViewPager.OnPageChangeListener {
//    private List<View> views;
    private OnPagerClickListener onPagerClickListener;
    LinearLayout llGuideGroup;
    int oldEventPosition;
    int currentItem;
    AutoScrollViewPager viewPager;
    Activity activity;
    LayoutInflater inflater;
    List<HomepageEntity.DataBean.HealthNumberArticleDTOSBean> datas;
    DoctorHealthHandler doctorHealthHandler;
    int thumbs = 0;
    long lastClickThumbs = 0;
    Message message;
    private boolean isInfiniteLoop = false;

    public DoctorHealthAdapter(List<HomepageEntity.DataBean.HealthNumberArticleDTOSBean> datas, Activity activity,AutoScrollViewPager viewPager,LinearLayout llGuideGroup,OnPagerClickListener onPagerClickListener) {
        if (datas == null){
            datas = new ArrayList<>();
        }
        this.onPagerClickListener = onPagerClickListener;
        this.llGuideGroup = llGuideGroup;
        this.viewPager = viewPager;
        this.activity = activity;
        this.datas = datas;
        this.inflater = activity.getLayoutInflater();
        doctorHealthHandler = new DoctorHealthHandler();
        initVpSign();
    }

    public void setOnPagerClickListener(OnPagerClickListener onPagerClickListener) {
        this.onPagerClickListener = onPagerClickListener;
    }



    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        HealthHolder healthHolder;
        if (convertView == null){
            convertView = inflater.inflate(R.layout.item_health_vp, null);
            healthHolder = new HealthHolder(convertView);
            convertView.setTag(healthHolder);
        }else{
            healthHolder = (HealthHolder) convertView.getTag();
        }
        HomepageEntity.DataBean.HealthNumberArticleDTOSBean healthNumberArticleDTOSBean = datas.get(position % ListUtil.getSize(datas));
        if (healthNumberArticleDTOSBean != null){
            Glide.with(activity)
                    .load(healthNumberArticleDTOSBean.getHealthNumberDoctorInfo().getAvatar())
                    .transform(new CenterCrop(),new CircleCrop())
                    .into(healthHolder.doctorHealthCardAvator);
            healthHolder.doctorHealthCardNameJob.setText(healthNumberArticleDTOSBean.getHealthNumberDoctorInfo().getName()+ " " + healthNumberArticleDTOSBean.getHealthNumberDoctorInfo().getTitleName());
            healthHolder.doctorHealthCardHospitalRoom.setText(healthNumberArticleDTOSBean.getHealthNumberDoctorInfo().getHospitalName() + " " + healthNumberArticleDTOSBean.getHealthNumberDoctorInfo().getDepartmentName());
            healthHolder.doctorHealthCardArticelTitle.setText(healthNumberArticleDTOSBean.getArticleTitle());
            healthHolder.doctorHealthCardArticelContent.setText(healthNumberArticleDTOSBean.getContent());
            healthHolder.doctorHealthCardArticelSign.setText(healthNumberArticleDTOSBean.getSource() == 1? "原创" : "转载");
            healthHolder.doctorHealthCardArticelSign.setBackgroundResource(healthNumberArticleDTOSBean.getSource() == 1? R.drawable.style_health_doctor_ycbg : R.color.color_F8F9FB);
            healthHolder.doctorHealthCardArticelTime.setText(healthNumberArticleDTOSBean.getPublishTime());
            Glide.with(activity)
                    .load(healthNumberArticleDTOSBean.getThumbsUp() == 1? R.mipmap.icon_health_good : R.mipmap.icon_health_ungood)
                    .transform(new CenterCrop())
                    .into(healthHolder.doctorHealthCardArticelGood);
            healthHolder.doctorHealthCardArticelGoodtxt.setText((healthNumberArticleDTOSBean.getThumbs() > 0 ? healthNumberArticleDTOSBean.getThumbs() > 999 ? "999+" : healthNumberArticleDTOSBean.getThumbs()+"" : "点赞"));
            healthHolder.doctorHealthCardArticelGoodtxt.setTextColor(healthNumberArticleDTOSBean.getThumbsUp() == 1 ?
                    activity.getResources().getColor(R.color.new_theme):activity.getResources().getColor(R.color.color_999));
            View finalConvertView = convertView;
            healthHolder.doctorHealthCard.setOnClickListener(v -> {onPagerClickListener.itemClick(finalConvertView,position % ListUtil.getSize(datas));});
            healthHolder.doctorHealthCardDoGood.setOnClickListener(v -> {
                //每次点赞本地缓存点赞次数
                thumbs ++ ;
//            datas.get(i).setThumbs(datas.get(i).getThumbs()+thumbs);
                healthHolder.doctorHealthCardArticelGoodtxt.setText((healthNumberArticleDTOSBean.getThumbs()+thumbs>999 ? "999+" : healthNumberArticleDTOSBean.getThumbs()+thumbs+""));
                healthHolder.doctorHealthCardArticelGoodtxt.setTextColor(activity.getResources().getColor(R.color.new_theme));
                Glide.with(activity)
                        .load(R.mipmap.icon_health_good)
                        .transform(new CenterCrop())
                        .into(healthHolder.doctorHealthCardArticelGood);
                //如果上次点赞距离当前超过1000ms 统计一次数据
                long l = System.currentTimeMillis();
                if (l-lastClickThumbs < 1000){
                    doctorHealthHandler.removeCallbacksAndMessages(null);
                }
                lastClickThumbs = l;
                message = new Message();
                message.what = 1;
                message.arg1 = position % ListUtil.getSize(datas);
                message.obj = thumbs;
                doctorHealthHandler.sendMessageDelayed(message,1000);
//            lastClickThumbs = l;
                //

            });

        }


//        View inflate = inflater.inflate(R.layout.item_health_vp, null);
//        Glide.with(activity)
//                .load(datas.get(i).getHealthNumberDoctorInfo().getAvatar())
//                .transform(new CenterCrop(),new CircleCrop())
//                .into((ImageView) inflate.findViewById(R.id.doctor_health_card_avator));
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_name_job)).setText(datas.get(i).getHealthNumberDoctorInfo().getName()+ " " + datas.get(i).getHealthNumberDoctorInfo().getTitleName());
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_hospital_room)).setText(datas.get(i).getHealthNumberDoctorInfo().getHospitalName() + " " + datas.get(i).getHealthNumberDoctorInfo().getDepartmentName());
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_articel_title)).setText(datas.get(i).getArticleTitle());
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_articel_content)).setText(datas.get(i).getContent());
//
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_articel_sign)).setText(datas.get(i).getSource() == 1? "原创" : "转载");
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_articel_sign)).setBackgroundResource(datas.get(i).getSource() == 1? R.drawable.style_health_doctor_ycbg : R.color.color_F8F9FB);
//        ((TextView)inflate.findViewById(R.id.doctor_health_card_articel_time)).setText(datas.get(i).getPublishTime());
//        Glide.with(activity)
//                .load(datas.get(i).getThumbsUp() == 1? R.mipmap.icon_health_good : R.mipmap.icon_health_ungood)
//                .transform(new CenterCrop())
//                .into((ImageView) inflate.findViewById(R.id.doctor_health_card_articel_good));
//        ((TextView) inflate.findViewById(R.id.doctor_health_card_articel_goodtxt)).setText((datas.get(i).getThumbs() > 0 ? datas.get(i).getThumbs() > 999 ? "999+" : datas.get(i).getThumbs()+"" : "点赞"));
//        ((TextView) inflate.findViewById(R.id.doctor_health_card_articel_goodtxt)).setTextColor(datas.get(i).getThumbsUp() == 1 ?
//                activity.getResources().getColor(R.color.new_theme):activity.getResources().getColor(R.color.color_999));
//        inflate.setOnClickListener(v -> {onPagerClickListener.itemClick(inflate,i);});
//        inflate.findViewById(R.id.doctor_health_card_do_good).setOnClickListener(v -> {
//            //每次点赞本地缓存点赞次数
//            thumbs ++ ;
////            datas.get(i).setThumbs(datas.get(i).getThumbs()+thumbs);
//            ((TextView) inflate.findViewById(R.id.doctor_health_card_articel_goodtxt)).setText((datas.get(i).getThumbs()+thumbs>999 ? "999+" : datas.get(i).getThumbs()+thumbs+""));
//            ((TextView) inflate.findViewById(R.id.doctor_health_card_articel_goodtxt)).setTextColor(activity.getResources().getColor(R.color.new_theme));
//            Glide.with(activity)
//                    .load(R.mipmap.icon_health_good)
//                    .transform(new CenterCrop())
//                    .into((ImageView) inflate.findViewById(R.id.doctor_health_card_articel_good));
//            //如果上次点赞距离当前超过1000ms 统计一次数据
//            long l = System.currentTimeMillis();
//            if (l-lastClickThumbs < 1000){
//                doctorHealthHandler.removeCallbacksAndMessages(null);
//            }
//            lastClickThumbs = l;
//            message = new Message();
//            message.what = 1;
//            message.arg1 = i;
//            message.obj = thumbs;
//            doctorHealthHandler.sendMessageDelayed(message,1000);
////            lastClickThumbs = l;
//            //
//
//        });

        return convertView;
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        llGuideGroup.getChildAt(oldEventPosition).setBackgroundResource(R.drawable.style_doctor_health_unsign);//黑色点
        llGuideGroup.getChildAt(position % ListUtil.getSize(datas)).setBackgroundResource(R.drawable.style_doctor_health_sign);//白色点
        oldEventPosition = position % ListUtil.getSize(datas);
        currentItem = position % ListUtil.getSize(datas);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public int getCount() {
        if (ListUtil.getSize(datas) > 0) {
            return isInfiniteLoop ? Integer.MAX_VALUE : ListUtil.getSize(datas);
        } else {
            return 0;
        }
    }


    public interface OnPagerClickListener{

        void itemClick(View view,int position);

        void itemChildClick(View view,int position);

        void itemThumbsUp(int thumbs,int position);

    }


    private void initVpSign() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(UIUtils.dp2px(activity, 6), UIUtils.dp2px(activity, 6));
        lp.leftMargin = 5;
        lp.rightMargin = 5;
        llGuideGroup.removeAllViews();
        for (int i = 0; i < datas.size(); i++) {
            ImageView imageView = new ImageView(llGuideGroup.getContext());
            imageView.setLayoutParams(lp);
            imageView.setBackgroundResource(i == 0 ? R.drawable.style_doctor_health_sign : R.drawable.style_doctor_health_unsign);
            llGuideGroup.addView(imageView);
        }
        viewPager.addOnPageChangeListener(this);
        viewPager.setInterval(2500);
        viewPager.startAutoScroll();
    }


    private class DoctorHealthHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                onPagerClickListener.itemThumbsUp(thumbs, msg.arg1);
                thumbs = 0;
            }
        }
    }

    public DoctorHealthAdapter setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
        return this;
    }

    public class HealthHolder{
        private ImageView doctorHealthCardAvator;
        private TextView doctorHealthCardNameJob;
        private TextView doctorHealthCardHospitalRoom;
        private TextView doctorHealthCardArticelTitle;
        private TextView doctorHealthCardArticelContent;
        private TextView doctorHealthCardArticelSign;
        private TextView doctorHealthCardArticelTime;
        private LinearLayout doctorHealthCardDoGood;
        private ImageView doctorHealthCardArticelGood;
        private TextView doctorHealthCardArticelGoodtxt;
        private CardView doctorHealthCard;

        public HealthHolder(View view){
            doctorHealthCardAvator = (ImageView) view.findViewById(R.id.doctor_health_card_avator);
            doctorHealthCardNameJob = (TextView) view.findViewById(R.id.doctor_health_card_name_job);
            doctorHealthCardHospitalRoom = (TextView) view.findViewById(R.id.doctor_health_card_hospital_room);
            doctorHealthCardArticelTitle = (TextView) view.findViewById(R.id.doctor_health_card_articel_title);
            doctorHealthCardArticelContent = (TextView) view.findViewById(R.id.doctor_health_card_articel_content);
            doctorHealthCardArticelSign = (TextView) view.findViewById(R.id.doctor_health_card_articel_sign);
            doctorHealthCardArticelTime = (TextView) view.findViewById(R.id.doctor_health_card_articel_time);
            doctorHealthCardDoGood = (LinearLayout) view.findViewById(R.id.doctor_health_card_do_good);
            doctorHealthCardArticelGood = (ImageView) view.findViewById(R.id.doctor_health_card_articel_good);
            doctorHealthCardArticelGoodtxt = (TextView) view.findViewById(R.id.doctor_health_card_articel_goodtxt);
            doctorHealthCard = (CardView) view.findViewById(R.id.doctor_health_card);
        }
    }
}
